import { isStatic } from '@/utils/common'
/**
 * 硬编码模拟页面数据，应用程序使用接口模拟数据后废弃
 */
import { generateAlarmData } from '@/utils/alarm'
/**
 * 模拟返回前端访问首页历史预警数据
 */
export function fetchUncheckAlarm() {
  return {
    data: [generateAlarmData(), generateAlarmData(), generateAlarmData()]
  }
}

/**
 * 模拟过滤查询全部预警数据
 * @param {Array} params 查询条件
 * @param {Array} defaultData 默认值
 */
export function fetchAlarmDatas(params, defaultData) {
  let retVal = []

  // 监所过滤器
  const filterRegion = ({ region }, item) => {
    return item.region === region
  }

  // 严重程度过滤器
  const filterLevel = ({ level }, item) => {
    return item.level === level
  }

  // 日期过滤器
  const filterDate = ({ fromAt, toAt }, item) => {
    return item.occurredAt >= fromAt && item.occurredAt <= toAt
  }

  let filters = []
  params.region && filters.push(filterRegion)
  params.level && filters.push(filterLevel)
  params.fromAt && filters.push(filterDate)

  if (filters.length) {
    retVal = defaultData.filter(item => {
      return filters.every(filter => {
        return filter(params, item)
      })
    })
  } else {
    retVal = defaultData.map(item => {
      return item
    })
  }

  let startIndex = params.pageSize * (params.currentPage - 1)
  startIndex >= retVal.length && (startIndex = 1)

  return {
    pageSize: params.pageSize,
    currentPage: params.currentPage,
    total: retVal.length,
    data: retVal.slice(startIndex, startIndex + params.pageSize)
  }
}

export const apiAlarm = params => {
  let url = isStatic() ? '/analysis.json' : '/alarm'
  if (!params) {
    return url
  }
  // `_page=${params.currentPage}&_limit=${params.pageSize}`
  let filters = []
  if (params.region) {
    filters.push(`region=${params.region}`)
  }
  if (params.level) {
    filters.push(`level=${params.level}`)
  }
  if (params.fromAt) {
    filters.push(`occurredAt_gte=${params.fromAt}`)
  }
  if (params.toAt) {
    filters.push(`occurredAt_lte=${params.toAt}`)
  }

  const orderMap = { ascending: 'asc', descending: 'desc' }
  const convertOrder = order => orderMap[order]
  let sort = params.sort || params.defaultSort

  if (sort) {
    let order = convertOrder(sort.order)
    filters.push(`_sort=${sort.prop}&_order=${order}`)
  }

  return url + '?' + filters.join('&')
}

export const apiInit = () => {
  return isStatic() ? '/analysis.json' : '/init'
}
